package commons;

/**
 * This is main class being which is called when the user clicks on 10^x button
 */
public class CalculatorAshwin {

	/** Main logic from here -- exp method is called after parsing into Double **/
	public Double pow(String str) {
		double pow = Double.parseDouble(str);
		if (isInteger(str)) {
			return optimizePower(10, pow);
		}

		return exp(pow);
	}

	private boolean isInteger(String inputValue) {
		try {
			int validate = Integer.parseInt(inputValue);
			if (validate < 0)
				return false;
		} catch (NumberFormatException e) {
			System.out.println(e.getMessage());
			return false;
		}
		return true;
	}

	/** If positive integer -- find by exponential square-roots **/
	public Double optimizePower(double ten, double power) {

		if (power == 1)
			return ten;
		if (power == 2)
			return ten * ten;
		if (power % 2 == 0) {
			return optimizePower(ten * ten, power / 2);
		} else if (power % 2 == 1) {
			return ten * optimizePower(ten * ten, (power - 1) / 2);
		}

		return ten;
	}

	/** Taylor Series Exponential function **/
	private double exp(double value) {
		double logTen = 2.302585092994046;
		value = logTen * value;
		double result = 0.0;
		double fact = 1.0;
		for (int i = 1; result != result + fact; i++) {
			result = result + fact;
			fact = fact * value / i;
		}
		return result;
	}

}
